package com.ruoyi.Ai.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/deepSeek")
@Slf4j
public class OpenAIController {

    @Value("${ai.config.deepseek.apiKey}")
    private String DEEPSEEK_API_KEY;

    @Value("${ai.config.deepseek.baseUrl}")
    private String DEEPSEEK_API_ENDPOINT;

    // 用于保存每个用户的对话历史
    private final Map<String, List<Map<String, String>>> conversationContext = new ConcurrentHashMap<>();

    private final ExecutorService taskExecutor = Executors.newCachedThreadPool();
    private final ObjectMapper jsonMapper = new ObjectMapper();

    @GetMapping()
    public ModelAndView chat(ModelAndView modelAndView) {
        modelAndView.setViewName("chat");
        return modelAndView;
    }

    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter handleChatRequest(@RequestBody String userQuestion) {
        String currentUserIdentifier = "123";

        SseEmitter responseEmitter = new SseEmitter(-1L);
        taskExecutor.execute(() -> {
            try {
                log.info("开始处理用户提问: {}", userQuestion);

                List<Map<String, String>> chatRecords = conversationContext.getOrDefault(currentUserIdentifier, new ArrayList<>());

                Map<String, String> userMessage = new HashMap<>();
                userMessage.put("role", "user");
                userMessage.put("content", userQuestion);

                Map<String, String> roleDefinition = new HashMap<>();
                roleDefinition.put("role", "system");
                roleDefinition.put("content", "源力星球智能AI助理。源力星球是一个资源共享平台，里面有着很多日常生活中用户使用的app，用户可通过这一个平台去下载自己所需要的资源，比如说去浏览器搜索Photoshop的话可以进到一下非官方的网站可以需要你付费或者下载下来后出现一下广告，或者说一些杂七杂八的软件，所以源力星球就是来解决这个问题的。");

                chatRecords.add(userMessage);
                chatRecords.add(roleDefinition);

                try (CloseableHttpClient apiClient = HttpClients.createDefault()) {
                    HttpPost apiRequest = new HttpPost(DEEPSEEK_API_ENDPOINT);
                    apiRequest.setHeader("Content-Type", "application/json");
                    apiRequest.setHeader("Authorization", "Bearer " + DEEPSEEK_API_KEY);

                    Map<String, Object> payload = new HashMap<>();
                    payload.put("model", "deepseek-chat");
                    payload.put("messages", chatRecords);
                    payload.put("stream", true);

                    String jsonPayload = jsonMapper.writeValueAsString(payload);
                    apiRequest.setEntity(new StringEntity(jsonPayload, StandardCharsets.UTF_8));

                    try (CloseableHttpResponse apiResponse = apiClient.execute(apiRequest);
                         BufferedReader streamReader = new BufferedReader(
                                 new InputStreamReader(apiResponse.getEntity().getContent(), StandardCharsets.UTF_8))) {

                        StringBuilder completeResponse = new StringBuilder();
                        String responseLine;

                        while ((responseLine = streamReader.readLine()) != null) {
                            if (responseLine.startsWith("data: ")) {
                                String eventData = responseLine.substring(6);
                                if ("[DONE]".equals(eventData)) {
                                    break;
                                }

                                JsonNode responseData = jsonMapper.readTree(eventData);
                                String deltaContent = responseData.path("choices")
                                        .path(0)
                                        .path("delta")
                                        .path("content")
                                        .asText("");

                                if (!deltaContent.isEmpty()) {
                                    responseEmitter.send(deltaContent);
                                    completeResponse.append(deltaContent);
                                }
                            }
                        }

                        Map<String, String> assistantMessage = new HashMap<>();
                        assistantMessage.put("role", "assistant");
                        assistantMessage.put("content", completeResponse.toString());
                        chatRecords.add(assistantMessage);

                        conversationContext.put(currentUserIdentifier, chatRecords);

                        log.info("完成用户提问处理: {}", userQuestion);
                        responseEmitter.complete();
                    }
                } catch (Exception processingException) {
                    log.error("DeepSeek API请求处理异常", processingException);
                    responseEmitter.completeWithError(processingException);
                }
            } catch (Exception generalException) {
                log.error("聊天请求处理异常", generalException);
                responseEmitter.completeWithError(generalException);
            }
        });

        return responseEmitter;
    }

}
